<template>
  <div>
    <el-table
      :data="dataArray"
      ref="multipleTable"
      highlight-current-row
      @select="select"
      @select-all="select"
      :header-cell-style="getRowClass"
      @selection-change="handleSelectionChange"
      @cell-dblclick="celldblclick"
      @current-change="currentChange"
      v-loading="loading"
    >
      <el-table-column v-if="tableParams.showMultiSelection"
                       type="selection"
                       :fixed="true"
                       width="32"
      >
      </el-table-column>
      <el-table-column label="单选" width="65" v-if="tableParams.showRadioSelection">
        <template slot-scope="scope">
          <el-radio class="radio"  v-model="radio"  :label="scope.$index"  @change.native="getTemplateRow(scope.$index,scope.row)">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column label="设为默认" width="80" v-if="tableParams.showDefault">
        <template slot-scope="scope">
          <el-radio class="radio" id="val"  v-model="radioA"  :label="scope.$index"  @change.native="getTemplateRow(scope.$index,scope.row)">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column v-for="(item,index_key) in tableParams.columnArray"
                       :label="item.label"
                       :width="item.width"
                       :prop="item.prop"
                       :column-key="item.prop"
                       :fixed="item.fixed"
                       :render-header="item.render"
                       :sortable="item.sortable"
                       :resizable="item.resizable"
                       :show-overflow-tooltip="!item.unShowTip"
                       :align="item.align"
                       :header-align="item.align"
                       :key="index_key"
      >
        <template slot-scope="scope">
          <a v-if="item.formatType === 'a'" style="color: #409EFF;"
             @click="handleClick(scope.row,item.prop)"
             href="javascript:void(0);">
            {{scope.row[item.prop]}}
          </a>
          <span v-else-if="item.formatType === 'input'">
                        <el-input v-model="scope.row[item.prop]" clearable></el-input>
                    </span>
          <span v-else-if="item.formatType === 'inputNum'">
                        <el-input-number v-model="scope.row[item.prop]"
                                         @blur="inputNumChange(scope.row[item.prop],item)"
                                         style="width: 100%"
                                         :precision="2"
                                         :step="item.step"
                                         size="size"
                                         :controls="false"
                                         :min="item.min"
                                         :max="item.max"></el-input-number>
                    </span>
          <span v-else-if="item.formatType === 'switch'">
            <el-switch
              v-model="scope.row[item.prop]"
              style="width: 100%"
              @change="switchChange"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </span>
          <span v-else v-html="scope.row[item.prop]"></span>
        </template>

      </el-table-column>

      <el-table-column label="操作" v-if="tableParams.showOperationColumn"
                       :width="tableParams.operationColumnWidth+'px'"
                       align="center"
                       :fixed="false"
                       header-align="center"
      >
        <template slot-scope="scope">
          <div v-if="scope.row['handleBtnArray'] && scope.row['handleBtnArray'].length>0">
            <el-button v-for="(item,index) in scope.row['handleBtnArray']" v-if="item.show" :key="index"
                       :type="item.type"
                       :disabled="item.disabled"
                       :loading="item.loading" :class="item.class" :style="item.style"
                       size="mini"
                       @click="handleOperation(scope.$index,scope.row,item.methodName,scope)">
              {{item.text}}
            </el-button>
          </div>
          <div v-else>
            <el-button v-for="(item,index) in colBtnArray" v-if="item.show" :key="index"
                       :type="item.type"
                       :disabled="item.disabled"
                       :loading="item.loading" :class="item.class" :style="item.style"
                       size="mini"
                       @click="handleOperation(scope.$index,scope.row,item.methodName,scope)">
              {{item.text}}
            </el-button>
            <el-dropdown v-if="colDropdownBtnArray.length>0"
                         @command="handleCommand">
                                <span class="el-dropdown-link">
                                   更多<i class="el-icon-arrow-down el-icon--right"></i>
                                </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item,index) in colDropdownBtnArray"
                                  v-if="item.show"
                                  :command="scope.$index+'#'+JSON.stringify(scope.row)+'#'+item.methodName"
                                  :key="index"
                                  :divided="item.divided">
                  {{item.text}}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination class="el-pagination" style="text-align:right;padding:20px 0;"
                   layout="total, prev, pager, next,sizes,jumper"
                   :total="page.total"
                   :current-page="page.currentPage"
                   @size-change="sizeChange"
                   @current-change="currentChange"
    >
    </el-pagination> -->
  </div>
</template>

<script>
  const viewBtn = {
    text: '查看',
    show: true,
    type: 'text',
    methodName: 'view'
  }
  const updateBtn = {
    text: '修改',
    show: true,
    type: 'text',
    methodName: 'update'
  }
  const deletedBtn =
    {
      text: '删除',
      show: true,
      type: 'text',
      methodName: 'delete'
    };
  export default {
    name: "VTable",
    props: {
      tableParams: {
        type: Object,
        required: true
      }
    }, data() {
      return {
        radio: '',
        radioA:0,
        loading:false,
        dataArray: [],
        alert: {
          show: false,
          type: '',
          title: '',
          description: ''
        },
        page: {
          currentPage: 1,
          pageSize: 50,
          total: 0,
        },
        colBtnArray: [],
        colDropdownBtnArray: [],
        viewBtn: {},
        updateBtn: {},
        deletedBtn: {}
      }
    },

    methods: {
      inputNumChange(value, item) {
        let totalPrice = 0;
        let totalElsePrice = 0;
        let totalNum = 0;
        this.dataArray.forEach(el => {
          if (item.prop === 'productPrice' ||
            item.prop === 'purNumber' || item.prop === 'elsePrice') {
            el.money = this.calculate.operation(el.productPrice, el.purNumber, '*');
          }
          totalPrice += el.money;
          totalElsePrice += el.elsePrice;
          totalNum += el.purNumber;
        });
        this.$emit("inputNumChange", {value: value, total: [totalPrice, totalNum, totalElsePrice]});
      },
      currentChange(currentRow) {
      },
      switchChange(val){
         this.$emit("switchChange",val)
      },
      handleSelectionChange(val) {
        this.$emit('handleSelectionChange', val);
      },
      select(selection, row) {
        this.$emit("singleChoose", selection, row)
      },
      handleOperation(rowIndex, row, methodName) {
        this.$emit('handleOperation', rowIndex, row, methodName);
      },
      handleCommand(command) {
        let array = command.split('#');
        this.handleOperation(array[0], JSON.parse(array[1]), array[2])
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
        this.page.currentPage = 1;
        this.getApiData();
      },
      getTemplateRow(index,row){
        this.$emit("getTemplateRow",index,row)
      },
      //设置表格第一行的颜色
      getRowClass({row, column, rowIndex, columnIndex}) {
        if (rowIndex == 0) {
            return 'background:#fafafa;color:rgba(0, 0, 0, 0.85);'
        } else {
            return ''
        }
      },
      handleClick(row, prop) {
        this.$emit('handleClick', row, prop);
      },
      //实现双击复制
      celldblclick(row, column, cell, event) {
        var _this = this
        this.$copyText(row[column.property]).then(function (e) {
          _this.$message.success("复制成功")
        }, function (e) {

        })
      },
      initButtonArray() {
        if (this.tableParams.rowHandle == null) {
          this.tableParams.rowHandle = {};
        }
        this.viewBtn = viewBtn;
        this.updateBtn = updateBtn;
        this.deletedBtn = deletedBtn;
        if (this.tableParams.rowHandle.view) {
          this.viewBtn = Object.assign({}, viewBtn, this.tableParams.rowHandle.view);
        }
        if (this.tableParams.rowHandle.update) {
          this.updateBtn = Object.assign({}, updateBtn, this.tableParams.rowHandle.update);
        }
        if (this.tableParams.rowHandle.deleted) {
          this.deletedBtn = Object.assign({}, deletedBtn, this.tableParams.rowHandle.deleted);
        }
        let defaultBtnArray = [this.viewBtn, this.updateBtn, this.deletedBtn];
        if (this.tableParams.rowHandle.buttonArray == null) {
          this.tableParams.rowHandle.buttonArray = defaultBtnArray;
        } else {
          this.tableParams.rowHandle.buttonArray = Object.assign({}, defaultBtnArray.concat(this.tableParams.rowHandle.buttonArray));
        }
        let btnArray = Object.values(this.tableParams.rowHandle.buttonArray);
        let hash = {};
        btnArray = btnArray.reduce(function (pre, next) {
          hash[next.text] ? '' : hash[next.text] = true && pre.push(next);
          return pre
        }, []);
        let count = 0;
        let numArray = [];
        btnArray.forEach(item => {
          if (!item.show) {
            numArray.push(count);
          }
          count++;
        });

        for (let index = 0; index < numArray.length; index++) {
          btnArray.splice(numArray[index] - index, 1);
        }
        if (btnArray.length > 3) {
          this.colBtnArray = btnArray.slice(0, 2);
          this.colDropdownBtnArray = btnArray.slice(2, btnArray.length);
        } else {
          this.colBtnArray = btnArray;
          this.colDropdownBtnArray = [];
        }
      },
    },
    created() {
      let index = 0;
      this.tableParams.columnArray.filter(item => {
        index++;
        if (item.show == null) {
          item.show = true;
        } else if (item.show === false) {
          this.tableParams.columnArray.splice(0, index);
        }
        return item;
      })

      if (this.tableParams.showOperationColumn == null) {
        this.tableParams.showOperationColumn = true;
      }
      if (this.tableParams.showMultiSelection == null) {
        this.tableParams.showMultiSelection = true;
      }
      if (this.tableParams.operationColumnWidth == null) {
        this.tableParams.operationColumnWidth = '140';
      }
      if (this.tableParams.searchParams == null) {
        this.tableParams.searchParams = {};
      }

      this.initButtonArray();
    }, watch: {
      'tableParams.dataArray'() {
        let array = Object.values(Object.assign({}, this.tableParams.dataArray));
        this.dataArray = array.slice((this.page.currentPage - 1) * this.page.pageSize, this.page.pageSize * this.page.currentPage);
        this.page.total = Object.values(this.tableParams.dataArray).length;
      }
    }
  }
</script>

<style scoped>
  .page-table-wrap .el-pagination {
    margin-top: 20px;
    text-align: right;
  }
  .el-alert-wrap {
    margin-bottom: 20px;
  }
  .el-table td {
    padding: 6px 0;
  }
</style>
